package com.haotunet.app.goldtreasure.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.VersionModel;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.views.UpdateDialog;
import com.haotunet.app.goldtreasure.views.UpdateDialog.OnAlterListener;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@SuppressWarnings("deprecation")
public class ApkUpdateControl {
    private Context mContext;
    private int mType;
    public static String downloadDir = Environment.getExternalStorageDirectory() + "/" + "goldTreasure";
    private Handler m_mainHandler;
    private String m_appNameStr;
    private ProgressDialog m_progressDlg;
    private static final int ON_UPDATE_COMPLETE = 1;
    private VersionModel model;
    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case ON_UPDATE_COMPLETE:
                    model = (VersionModel) msg.obj;
                    String enforce = model.getIsEnforce();
                    if (enforce.equals("-1")) {
                        if (mType == 2) {
                            UIHelper.showToast(mContext, "已是最新版本!");
                        }
                    } else {
                        showUpdateDialog(enforce);
                    }
                    break;
                default:
                    break;
            }
        }

    };
    private UpdateDialog updateDialog;
    private static ApkUpdateControl instance = null;

    private ApkUpdateControl() {

    }

    private void showUpdateDialog(String enforce) {
        if (enforce.equals("0")) {
            updateDialog = new UpdateDialog(mContext, model.getVersionNote(), new String[]{"更新", "暂不更新"},
                    R.style.FullDialog,1);
            updateDialog.setAlterListener(new OnAlterListener() {

                @Override
                public void positive() {
                    m_progressDlg.setTitle("开始加载");
                    m_progressDlg.setMessage("请稍候...");
                    downFile(model.getDownload());
                }

                @Override
                public void nagative() {
                    updateDialog.dismiss();
                }
            });
            updateDialog.show();
        } else if (enforce.equals("1")) {
            updateDialog = new UpdateDialog(mContext, model.getVersionNote(), new String[]{"更新"},
                    R.style.FullDialog,2);
            updateDialog.setAlterListener(new OnAlterListener() {

                @Override
                public void positive() {
                    m_progressDlg.setTitle("开始加载");
                    m_progressDlg.setMessage("请稍候...");
                    downFile(model.getDownload());
                }

                @Override
                public void nagative() {

                }

            });
            updateDialog.show();
        }
    }

    private void initVariable() {
        m_mainHandler = new Handler();
        m_progressDlg = new ProgressDialog(mContext);
        m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
        m_progressDlg.setIndeterminate(false);
        m_appNameStr = "goldTreasure.apk";
    }

    public synchronized static ApkUpdateControl getInstance() {

        if (instance == null) {
            instance = new ApkUpdateControl();

        }
        return instance;
    }

    public void checkVersion(final Activity context, int type) {
        mContext = context;
        mType = type;
        initVariable();
        String versionName = Config.getVersionName(context);
        int versionCode = Config.getVersionCode(context);
        String channel_name = Config.getStringMetaData(context, "UMENG_CHANNEL");
        ActionUtil actionUtil = new ActionUtil(context);
        actionUtil.checkVersion(channel_name, versionCode,versionName);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                VersionModel versionModel = (VersionModel) model;
                if (versionModel == null) {
                    UIHelper.showToast(context, context.getString(R.string.rank_fail));
                    return;
                }
                if (versionModel.getErrorMsg() != null) {
                    UIHelper.showToast(context, versionModel.getErrorMsg());
                } else {
                    Message msg = new Message();
                    msg.what = ON_UPDATE_COMPLETE;
                    msg.obj = versionModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void downFile(final String url) {
        m_progressDlg.show();
        new Thread() {

            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();

                    m_progressDlg.setMax((int) length);// 设置进度条的最大值

                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(), m_appNameStr);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) {
                                m_progressDlg.setProgress(count);
                            }
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down(); // 告诉HANDER已经下载完成了，可以安装了
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void down() {
        m_mainHandler.post(new Runnable() {
            public void run() {
                m_progressDlg.cancel();
                update();
            }
        });

    }

    private void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), m_appNameStr)),
                "application/vnd.android.package-archive");
        mContext.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
